package api

import (
	"bufio"
	"encoding/json"
	"log"
	"os"
)

type ConfigParser struct {
	configMap map[string]interface{}
}

func NewConfigParser() *ConfigParser {
	return &ConfigParser{
		configMap: map[string]interface{}{},
	}
}

func (_this *ConfigParser) Add(id string, mod interface{}) {
	if id == "" {
		log.Fatal("id is invalid")
		return
	}
	if mod == nil {
		log.Fatal("mod is nil")
		return
	}
	_, ok := _this.configMap[id]
	if ok {
		log.Fatal("id is registed")
		return
	}
	_this.configMap[id] = mod
}

func (_this *ConfigParser) GetConfig(id string) interface{} {
	if id == "" {
		log.Fatal("id is invalid")
		return nil
	}
	mod := _this.configMap[id]
	if mod == nil {
		log.Fatal("mod is nil")
		return nil
	}
	cfg, error := _parseJsonConfig(id, mod)
	if error != nil {
		log.Fatal(error)
		return nil
	}
	return cfg
}

func _parseJsonConfig(path string, mod interface{}) (interface{}, error) {

	file, error := os.Open(path)
	if error != nil {
		panic(error)
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	decoder := json.NewDecoder(reader)
	if error = decoder.Decode(mod); error != nil {
		return nil, error
	}
	return mod, nil
}
